﻿package co.th.bjc.md.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import co.th.bjc.md.dao.BJCDepartment;
import co.th.bjc.md.dao.Brand;
import co.th.bjc.md.dao.Category;
import co.th.bjc.md.dao.CustomerData;
import co.th.bjc.md.dao.Department;
import co.th.bjc.md.dao.Hospital;
import co.th.bjc.md.dao.HospitalDepartment;
import co.th.bjc.md.dao.Images;
import co.th.bjc.md.dao.Model;
import co.th.bjc.md.process.service.CallService;
import co.th.bjc.md.service.interfaces.CustomerDataManageService;
import co.th.bjc.md.service.interfaces.ProductManageService;

import net.sf.json.JSONArray;

/**
 * Servlet implementation class CustomerDataManageServlet
 */
public class CustomerDataManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CustomerDataManageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=UTF-8");
		JSONArray jsonObject = new JSONArray();
		boolean status = false;
		String action = request.getParameter("action")==null?"":request.getParameter("action");
		
		if(action.equals("SEARCH")){
			PrintWriter out = response.getWriter();
			jsonObject = this.getSearchResult(request, response);
			out.print(jsonObject);
		}else if(action.equals("DELETE")){
			// Delete process
			if(this.delete(request, response)){
				PrintWriter out = response.getWriter();
				status = true;
				jsonObject = this.getSearchResult(request, response);
				jsonObject.add(status);
				out.print(jsonObject);
			}
		}else if(action.equals("GETEDIT")){
			PrintWriter out = response.getWriter();
			jsonObject = getEditItem(request, response);
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
		}else if(action.equals("GETVIEW")){
			PrintWriter out = response.getWriter();
			jsonObject = getViewItem(request, response);
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
		}else if(action.equals("GETHOSPITAL")){
			PrintWriter out = response.getWriter();
			int regionId = Integer.parseInt(request.getParameter("id"));
			jsonObject = getHospitalList(regionId);
			out.print(jsonObject);
		}else if(action.equals("GETHOSPITALDEPARTMENT")){
			PrintWriter out = response.getWriter();
			String hospitalCode = request.getParameter("id");
			jsonObject = getHospitalDepartmentList(hospitalCode);
			out.print(jsonObject);
		}else if(action.equals("GETHOSPITALDEPARTMENTDETAIL")){
			PrintWriter out = response.getWriter();
			String hospitalCode = request.getParameter("hospitalCode");
			String departmentCode = request.getParameter("departmentCode");
			jsonObject = getHospitalDepartmentDetail(hospitalCode, departmentCode);
			out.print(jsonObject);
		}else if(action.equals("GETIMG")){
			getBlob(request, response);
		}else if(action.equals("GETRECORDS")){
			PrintWriter out = response.getWriter();
			jsonObject = getTotalRecord(request);
			out.print(jsonObject);
		}else if(action.equals("GETBJCDEPARTMENT")){
			PrintWriter out = response.getWriter();
			jsonObject = getBJCDepartment();
			out.print(jsonObject);
		}else if(action.equals("GETCATEGORY")){
			PrintWriter out = response.getWriter();
			jsonObject = getCategory();
			out.print(jsonObject);
		}else if(action.equals("GETBRAND")){
			PrintWriter out = response.getWriter();
			BigDecimal categoryCode = BigDecimal.valueOf(Long.parseLong(request.getParameter("categoryCode")));
			jsonObject = getBrand(categoryCode);
			out.print(jsonObject);
		}else if(action.equals("GETMODEL")){
			PrintWriter out = response.getWriter();
			BigDecimal brandCode = BigDecimal.valueOf(Long.parseLong(request.getParameter("brandCode")));
			jsonObject = getModel(brandCode);
			out.print(jsonObject);
		}else{
			getServletContext().getRequestDispatcher("/jsp/datamanage/manage_customerdata_main.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		JSONArray jsonObject = new JSONArray();
		boolean status = false;
		try {
	        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
	        for (FileItem item : items) {
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	            	String fieldname = item.getFieldName();
	            	String fieldValue = item.getString();
	            	if(fieldname.equals("action")){
	            		if(fieldValue.equals("INSERT")){
	            			// Insert process
	            			if(this.insert(items)){
	            				status = true;
	            				jsonObject = this.getSearchResult(request, response);
	            				jsonObject.add(status);
	            				out.print(jsonObject);
	            			}
	            		}
	            		break;
	            	}
	            }
	        }
	    }  catch (FileUploadException e) {
	        e.printStackTrace();
	    }
	}
	
	private JSONArray getSearchResult(HttpServletRequest request, HttpServletResponse response) {
		String type = request.getParameter("srh_type") == null?"":request.getParameter("srh_type");
		String department = request.getParameter("srh_type") == null?"":request.getParameter("srh_department");
		int minBed = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_bed_min"));
		int maxBed = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_bed_max"));
		int presidentImpRate = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_imp_rate_president"));
		int presidentRpRate = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_rp_rate_president"));
		int directorImpRate = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_imp_rate_director"));
		int directorRpRate = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_rp_rate_director"));
		int limitFrom = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("limitFrom"));
		int limitTo = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("limitTo"));
		
		CustomerDataManageService services = (CustomerDataManageService) CallService.getService("customerdatamanage");
		List<CustomerData> list = services.getCustomerDataList(type, department, minBed, maxBed, presidentImpRate, presidentRpRate, directorImpRate, directorRpRate, limitFrom, limitTo);
		JSONArray jsonObject = JSONArray.fromObject(list);
		return jsonObject;
	}
	
	private JSONArray getTotalRecord(HttpServletRequest request){
		String type = request.getParameter("srh_type") == null?"":request.getParameter("srh_type");
		String department = request.getParameter("srh_type") == null?"":request.getParameter("srh_department");
		int minBed = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_bed_min"));
		int maxBed = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_bed_max"));
		int presidentImpRate = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_imp_rate_president"));
		int presidentRpRate = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_rp_rate_president"));
		int directorImpRate = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_imp_rate_director"));
		int directorRpRate = request.getParameter("srh_type") == null?0:Integer.parseInt(request.getParameter("srh_rp_rate_director"));
		CustomerDataManageService services = (CustomerDataManageService) CallService.getService("customerdatamanage");
		Integer count = services.countTotalRecord(type, department, minBed, maxBed, presidentImpRate, presidentRpRate, directorImpRate, directorRpRate);
		JSONArray jsonObject = JSONArray.fromObject(count);
		return jsonObject;
	}
	
	private boolean insert(List<FileItem> items) {
		CustomerData cus = new CustomerData();
		boolean status = false;
		try{
			for (FileItem item : items) {
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	                String fieldname = item.getFieldName();
	                String fieldvalue = item.getString();
	                switch(fieldname){
	                	case "ins_customerdata_code": cus.setCustomerDataCode(fieldvalue);break;
	                	case "ins_region_name": cus.setRegion(fieldvalue);break;
	                	case "ins_hospital_name_name_th": cus.setHospitalNameTh(fieldvalue);break;
	                	case "ins_hospital_name_name_en": cus.setHospitalNameEn(fieldvalue);break;
	                	case "ins_hospital_department_name": cus.setHospitalDepartment(fieldvalue);break;
	                	case "ins_type": cus.setType(fieldvalue);break;
	                	case "ins_bed_min": cus.setBedCapacityMin(Integer.parseInt(fieldvalue));break;
	                	case "ins_bed_max": cus.setBedCapacityMax(Integer.parseInt(fieldvalue));break;
	                	case "ins_hospital_address": cus.setHospitalAddress(fieldvalue);break;
	                	case "ins_hospital_telephone": cus.setHospitalTelephone(fieldvalue);break;
	                	case "ins_hospital_email": cus.setHospitalEmail(fieldvalue);break;
	                	case "ins_president_name": cus.setPresidentName(fieldvalue);break;
	                	case "ins_president_telephone": cus.setPresidentTelephone(fieldvalue);break;
	                	case "ins_president_email": cus.setPresidentEmail(fieldvalue);break;
	                	case "ins_imp_rate_president": cus.setPresidentImpRate(Integer.parseInt(fieldvalue));break;
	                	case "ins_rp_rate_president": cus.setPresidentRpRate(Integer.parseInt(fieldvalue));break;
	                	case "ins_director_name": cus.setDirectorName(fieldvalue);break;
	                	case "ins_director_telephone": cus.setDirectorTelephone(fieldvalue);break;
	                	case "ins_director_email": cus.setDirectorEmail(fieldvalue);break;
	                	case "ins_imp_rate_director": cus.setDirectorImpRate(Integer.parseInt(fieldvalue));break;
	                	case "ins_rp_rate_director": cus.setDirectorRpRate(Integer.parseInt(fieldvalue));break;
	                	case "ins_remark1": cus.setRemark1(fieldvalue);break;
	                	case "ins_bjc_department": cus.setBjcDepartment(fieldvalue);break;
	                	case "ins_sale_person": cus.setSalePerson(fieldvalue);break;
	                	case "ins_bjc_category": cus.setBjcCategory(fieldvalue);break;
	                	case "ins_bjc_brand": cus.setBjcBrand(fieldvalue);break;
	                	case "ins_bjc_model": cus.setBjcModel(fieldvalue);break;
	                	case "ins_st_competitor": cus.setStCompetitor(fieldvalue);break;
	                	case "ins_nd_competitor": cus.setNdCompetitor(fieldvalue);break;
	                	case "ins_rd_competitor": cus.setRdCompetitor(fieldvalue);break;
	                	case "ins_remark2": cus.setRemark2(fieldvalue);break;
	                }
	            } else {
	                // Process form file field (input type="file").
	                String filename = FilenameUtils.getName(item.getName());
	                if(!filename.equals("")){
						InputStream filecontent = item.getInputStream();
						cus.setImg(filecontent);
	                }
	            }
	        }
			CustomerDataManageService service = (CustomerDataManageService) CallService.getService("customerdatamanage");
			status = service.addCustomerData(cus);
		}  catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return status;
	}
	
	private boolean update(HttpServletRequest request, HttpServletResponse response) {
		return false;
	}
	
	private boolean delete(HttpServletRequest request, HttpServletResponse response){
		return false;
	}
	
	private JSONArray getEditItem(HttpServletRequest request, HttpServletResponse response){
		BigInteger id = BigInteger.valueOf(Long.parseLong(request.getParameter("id")));
		CustomerDataManageService services = (CustomerDataManageService) CallService.getService("customerdatamanage");
		CustomerData obj = services.getEditCustomerData(id);
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}
	
	private JSONArray getViewItem(HttpServletRequest request, HttpServletResponse response){
		BigInteger id = BigInteger.valueOf(Long.parseLong(request.getParameter("id")));
		CustomerDataManageService services = (CustomerDataManageService) CallService.getService("customerdatamanage");
		CustomerData obj = services.getViewCustomerData(id);
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}
	
	private JSONArray getHospitalList(int regionId){
		CustomerDataManageService services = (CustomerDataManageService) CallService.getService("customerdatamanage");
		List<Hospital> list = services.getHostpitalList(regionId);
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private JSONArray getHospitalDepartmentList(String hospitalCode){
		CustomerDataManageService services = (CustomerDataManageService) CallService.getService("customerdatamanage");
		List<HospitalDepartment> list = services.getDepartmentList(hospitalCode);
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private JSONArray getHospitalDepartmentDetail(String hospitalCode, String departmentCode){
		CustomerDataManageService services = (CustomerDataManageService) CallService.getService("customerdatamanage");
		Hospital obj = services.getHospitalDepartmentDetail(hospitalCode, departmentCode);
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}
	
	private void getBlob(HttpServletRequest request, HttpServletResponse response) throws IOException{
		CustomerDataManageService services = (CustomerDataManageService) CallService.getService("customerdatamanage");
		InputStream in = services.getImgBlob(BigInteger.valueOf(Long.parseLong(request.getParameter("imageId"))));
		byte[] bytes = IOUtils.toByteArray(in);
		if(bytes.length > 0){
		    response.setContentType("image/jpeg");
		    OutputStream outputStream = response.getOutputStream();
		    outputStream.write(bytes);
		    outputStream.flush();
		    outputStream.close();
		}
	}
	
	private JSONArray getBJCDepartment(){
		Department obj = new Department();
		obj.setDepartmentCode(1);
		obj.setDepartmentName("TEST");
		List<Department> list = new ArrayList<>();
		list.add(obj);
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private JSONArray getCategory(){
		Category obj = new Category();
		obj.setCategoryCode(BigDecimal.valueOf(1));
		obj.setCategoryName("Car");
		List<Category> list = new ArrayList<>();
		list.add(obj);
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private JSONArray getBrand(BigDecimal categoryCode){
		Brand obj = new Brand();
		obj.setBrandCode(BigDecimal.valueOf(1));
		obj.setBrandName("Toyota");
		List<Brand> list = new ArrayList<>();
		list.add(obj);
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private JSONArray getModel(BigDecimal brandCode){
		Model obj = new Model();
		obj.setModelCode(BigDecimal.valueOf(1));
		obj.setModelName("Vios");
		List<Model> list = new ArrayList<>();
		list.add(obj);
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}

}
